package club.mzywucai.blog.file_system.service.impl;

import club.mzywucai.blog.file_system.mapper.DownloadAndStarCountMapper;
import club.mzywucai.blog.file_system.pojo.domain.JsonData;
import club.mzywucai.blog.file_system.pojo.vo.UserVo;
import club.mzywucai.blog.file_system.service.DownloadAndStarCountService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;

import javax.servlet.http.HttpSession;

/**
 * @author mzywucai
 * @Description 点赞数统计和下载数统计
 * @date 2019/2/12
 */
@Service
public class DownloadAndStarCountServiceImpl implements DownloadAndStarCountService {
    @Autowired
    DownloadAndStarCountMapper downloadAndStarCountMapper;

    @Transactional(propagation= Propagation.REQUIRED)
    @Override
    public JsonData countStar(long fileInfoId, HttpSession session) {
        UserVo user = (UserVo) session.getAttribute("user");
        if (null == user) {
            return JsonData.buildError("请先登录再进行点赞");
        }

        Long userId = user.getUserId();

        int res = downloadAndStarCountMapper.searchStarIsExist(fileInfoId, userId);

        if (res != 0) {
            return JsonData.buildSuccess(1, "warning", "您已经点过赞了");
        }

        downloadAndStarCountMapper.addStarRecord(fileInfoId, userId);
        downloadAndStarCountMapper.updateFileInfoTableStarCount(fileInfoId);

        return JsonData.buildSuccess(0, "ok", "点赞成功");
    }

    /**
     * @Description 下载数 静默记录。
     * @author mzywucai
     * @time 2019-02-12
     * @see 
     * @return   club.mzywucai.blog.file_system.pojo.domain.JsonData
     * @params  [fileInfoId, session]
     */
    @Transactional(propagation= Propagation.REQUIRED)
    @Override
    public JsonData countDownload(long fileInfoId, HttpSession session) {
        UserVo user = (UserVo) session.getAttribute("user");
        if (null == user) {
            return JsonData.buildError("请先登录再进行下载");
        }

        Long userId = user.getUserId();

        int res = downloadAndStarCountMapper.searchDownloadIsExist(fileInfoId, userId);

        if (res != 0) {
            // 不是第一次下载，不记录
            return JsonData.buildSuccess(1, "ok", "");
        }

        downloadAndStarCountMapper.addDownloadRecord(fileInfoId, userId);
        downloadAndStarCountMapper.updateFileInfoTableDownloadCount(fileInfoId);

        return JsonData.buildSuccess(0, "ok", "");
    }
}
